package com.aoip.telemetry.telemetry.core.util;

import com.aoip.telemetry.telemetry.core.config.RuoYiConfig;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;

/**
 * 加载bean工具类
 *
 * @author chenbai
 * @version 1.0
 * @date 2022/4/15 9:29
 */
@Component
public class LoadBeanUtil {

//    public T loadBeanFromJar(String beanName, String filePath) throws MalformedURLException {
//
////        String protocolFilePath = protocol.getProtocolFilePath();
//        String downloadPath = RuoYiConfig.getProfile();
////        String beanName = protocolEntry.substring(0, 1).toLowerCase() + protocolEntry.substring(1);
////        protocolFilePath = protocolFilePath.replaceFirst("/profile", "");
//        String jarPath = downloadPath + filePath;
//        File jar = new File(jarPath);
//        URI uri = jar.toURI();
////        String moduleName = jarPath.substring(jarPath.lastIndexOf("\\") + 1, jarPath.lastIndexOf("."));
//        ModuleClassLoader classLoader = new ModuleClassLoader(new URL[]{uri.toURL()}, Thread.currentThread().getContextClassLoader());
//        SpringUtil.getBeanFactory().setBeanClassLoader(classLoader);
//        Thread.currentThread().setContextClassLoader(classLoader);
//        classLoader.initBean();
//        List<String> beanList = classLoader.getRegisteredBean();
//        for (String s : beanList) {
//            if (s.equals(beanName)) {
//                return SpringUtil.getBean(beanName);
//            }
//        }
//        return null;
//    }

    public ModuleClassLoader registerBean(String filePath) throws MalformedURLException {
        String downloadPath = RuoYiConfig.getProfile();
        String jarPath = downloadPath + filePath;
        File jar = new File(jarPath);
        URI uri = jar.toURI();
        ModuleClassLoader classLoader = new ModuleClassLoader(new URL[]{uri.toURL()}, Thread.currentThread().getContextClassLoader());
        SpringUtil.getBeanFactory().setBeanClassLoader(classLoader);
        Thread.currentThread().setContextClassLoader(classLoader);

        return classLoader;
    }
}
